package com.bwc.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bwc.common.BaseContext;
import com.bwc.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;




import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//       向下转型为HttpServletRequest 主要是为了获得request的一些参数信息，ServletRequest没办法获得这些信息，例如request.getSession ,request.getRequestURI
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        1、获取本次请求的URI
        String servletURI = request.getRequestURI();
//        log.info("拦截到请求：{}",request.getRequestURI());

        //定义哪些需要放行的路径
//        String[] urls = {"/employee/login","/employee/logout","/backend/**,/front/**"};
//逻辑：放行所有静态资源，如果在未登入的情况下，访问一些静态资源，由于静态资源又会自动发送一些动态资源的请求，所以就会跳转到登入界面

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
//        2、判断本次请求是否需要处理
        boolean checkResult = check(urls,servletURI);
//        System.out.println(checkResult);
//        3、如果不需要处理，就放行
        if(checkResult){
//            log.info("本次请求不需要处理：{}",request.getRequestURI());
            filterChain.doFilter(request,response);
            return;
        }
//       4-1、判断登入状态，如果是用户已经登入了，有了登入的信息，那么不管访问什资源（静态的 or 动态的）都放行
//        上面那个是，只要访问相关的登入志愿，或者静态志愿，都让放行，毕竟可以重复登入
        if(request.getSession().getAttribute("employee")!=null){
//            log.info("用户已登入，id为：{}",request.getSession().getAttribute("employee"));
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }

        //4-2、判断移动端用户登入状态
        if(request.getSession().getAttribute("user")!=null){
//            log.info("用户已登入，id为：{}",request.getSession().getAttribute("employee"));
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }

//        5、如果没有登入，又想访问不是上面urls的资源，则直接跳转
//        log.info("如果没有登入，又想访问不是上面urls的资源");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 检查本次请求是否需要放行，true 放行；
     * @param urls
     * @param servletURI
     * @return
     */
    public boolean check(String[] urls,String servletURI){
        for(String url : urls){
            boolean match = PATH_MATCHER.match(url,servletURI);
            if(match){
                return true;
            }
        }
        return false;
    }

}
